package com.blog.security;

import com.blog.entity.User;
import com.blog.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

@Component
public class RoleChecker {
    private static final Logger logger = LoggerFactory.getLogger(RoleChecker.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    public void checkAdminRole(String token) {
        if (token == null) {
            logger.error("Token is null");
            throw new AccessDeniedException("未提供认证令牌");
        }

        String username = jwtTokenProvider.getUsernameFromJWT(token);
        if (username == null) {
            logger.error("Could not extract username from token");
            throw new AccessDeniedException("无效的认证令牌");
        }

        User user = userService.findByUsername(username);
        if (user == null) {
            logger.error("User not found: {}", username);
            throw new AccessDeniedException("用户不存在");
        }

        if (!userService.isAdmin(user)) {
            logger.error("User {} does not have admin role", username);
            throw new AccessDeniedException("需要管理员权限");
        }

        logger.info("Admin role check passed for user: {}", username);
    }
}